﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

namespace UnityDependencyResolver.Lib
{
  public class UnityWebApiDependencyResolver : IDependencyResolver
  {
    readonly IUnityContainer _container;
    readonly SharedDependencyScope _sharedScope;

    public UnityWebApiDependencyResolver(IUnityContainer container)
    {
      _container = container;
      _sharedScope = new SharedDependencyScope(container);
    }

    public IDependencyScope BeginScope()
    {
      return _sharedScope;
    }

    public object GetService(Type serviceType)
    {
      if (_container.IsRegistered(serviceType))
        return _container.Resolve(serviceType);
      else
        return null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
      return _container.ResolveAll(serviceType);
    }

    public void Dispose()
    {
      _container.Dispose();
      _sharedScope.Dispose();
    }
  }

  public class SharedDependencyScope : IDependencyScope
  {
    private IUnityContainer container;

    public SharedDependencyScope(IUnityContainer container)
    {
      this.container = container;
    }

    public object GetService(Type serviceType)
    {
      return this.container.Resolve(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
      return this.container.ResolveAll(serviceType);
    }

    public void Dispose()
    {
      // NO-OP, as the container is shared.
    }
  }
}